#include "hismana.h"
#include "ui_hismana.h"
#include<QDebug>
#include<QMessageBox>
#include <QDialog>
#include <QFormLayout>
#include <QLineEdit>
#include <QDialogButtonBox>
#include <QVBoxLayout>
#include <QMessageBox>
#include <QSqlQuery>
HisMana::HisMana(QSqlDatabase &d) :
//    QWidget(parent),
    db(d),
    ui(new Ui::HisMana)
{
    ui->setupUi(this);
    nowMode=bNameMode;
    if(db.open())
    {
        qDebug() << "连接成功";
    }
    d_model=new QSqlTableModel(this,db);
    d_model->setTable("borrow_h");
    ui->tableView->setEditTriggers(QTableView::NoEditTriggers);//设置不能编辑表格
//    ui->tableView->setEditTriggers(QTableView::DoubleClicked);//设置双击后可以编辑
    getAll();
}

HisMana::~HisMana()
{
    delete ui;
}


void HisMana::on_rueBut_clicked()
{
    d_model->submitAll();
    getAll();
}

void HisMana::on_findBut_clicked()
{
    QString search = ui->searchEdit->text();

    // 根据条件查询
    QSqlQueryModel *queryModel = new QSqlQueryModel(this);
    if(nowMode==bNoMode)
        queryModel->setQuery(QString("select bo.* from book b right join borrow_h bo on b.B_Id = bo.L_Book WHERE B_Id LIKE '%1';")
                         .arg(search), db);
    if(nowMode==bNameMode)
        queryModel->setQuery(QString("select bo.* from book b right join borrow_h bo on b.B_Id = bo.L_Book WHERE B_Name LIKE '%%1%';")
                         .arg(search), db);
    if(nowMode==cNameMode)
        queryModel->setQuery(QString("select bo.* from book b right join borrow_h bo on b.B_Id = bo.L_Book WHERE B_Cou LIKE '%%1%';")
                         .arg(search), db);
    if (queryModel->lastError().type() != QSqlError::NoError) {
        qDebug() << "查询错误:" << queryModel->lastError();
        QMessageBox::critical(this, tr("错误"), tr("查询失败：") + queryModel->lastError().text());
        return;
    }

    // 显示查询结果
    ui->tableView->setModel(queryModel);
    QStringList chineseHeaders;
    chineseHeaders <<tr("借阅编号") << tr("联系方式") << tr("学号")<< tr("图书编号")<< tr("数量")<< tr("借阅日期")<< tr("归还日期");
    for (int i = 0; i < chineseHeaders.size(); ++i) {
        queryModel->setHeaderData(i, Qt::Horizontal, chineseHeaders[i]);
    }
    ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);

}


void HisMana::getAll()
{
    if(!d_model->select()){
        qDebug()<<"连接错误";
    }
    ui->tableView->setModel(d_model);
    // 设置中文表头
        QStringList chineseHeaders;
        chineseHeaders <<tr("借阅编号") << tr("联系方式") << tr("学号")<< tr("图书编号")<< tr("数量")<< tr("借阅日期")<< tr("归还日期");
        for (int i = 0; i < chineseHeaders.size(); ++i) {
            d_model->setHeaderData(i, Qt::Horizontal, chineseHeaders[i]);
        }

        ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);

}



void HisMana::on_comboBox_currentTextChanged(const QString &arg1)
{
    if(arg1=="图书编号"){
        nowMode = bNoMode;
    }
    else if(arg1=="书名"){
        nowMode = bNameMode;
    }
    else if(arg1=="出版社"){
        nowMode = cNameMode;
    }
}
